<template>
  <div class="manage_accounts">
    <el-dialog title="Manage Accounts"
               :close-on-click-modal="false"
               :visible.sync="dialogVisible"
               @open="init"
               width="920px"
               :before-close="handleClose">
      <div class="accounts_conditions">
        <el-input :placeholder="$t('custom.attendance.record.search.search')"
                  @input="searchTemp"
                  prefix-icon="el-icon-search"
                  v-model="filterText">
        </el-input>
        <el-popover width="230"
                    @hide="addPopverClose"
                    popper-class="manage_accounts_addtemp"
                    v-model="visible">
          <el-form :model="dataForm"
                   :rules="dataRule"
                   :inline="false"
                   ref="newMappingForm"
                   @submit.native.prevent
                   label-width="80px"
                   label-position="top">
            <!-- <el-form-item>
                  <div class="report_intor">Name your new custom report and select the widgets to be used in the report on the next page.</div>
                </el-form-item> -->
            <el-form-item prop="name"
                          :label="$t('custom.reports.name')">
              <el-input :placeholder="$t('custom.mapping.enter')"
                        v-model="dataForm.name">
              </el-input>
            </el-form-item>
            <el-form-item prop="type"
                          :label="$t('custom.reports.template_calss')">
              <el-select v-model="dataForm.type"
                         @change="tempalteChange"
                         :placeholder="$t('custom.mapping.pleaseSelect')">
                <el-option v-for="item in options"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-checkbox style="margin-right:10px"
                           v-model="checked"></el-checkbox> <span>{{$t('custom.mapping.copyFrom')}}</span>
            </el-form-item>
            <el-form-item prop="tempId"
                          v-if="checked">
              <el-select v-model="dataForm.tempId"
                         :placeholder="$t('oss.qcloudRegionTips')"
                         popper-class="manage_account_selecet">
                <el-option v-for="(item,index) in copyTempDateList"
                           :key="index"
                           :label="item.name"
                           :value="item.id">
                  <div style="display:flex;justify-content: space-between;align-items: center;"><span>{{item.name}}</span>
                    <div class="temp_share_text" v-if="!item.modifyFlag"><span>{{$t('custom.mapping.buildInTemplate')}}</span></div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         size="small"
                         v-loading="addLoading"
                         @click="dataFormSubmitHandle()">{{ $t('custom.reports.continue') }}</el-button>
            </el-form-item>
          </el-form>
          <div slot="reference"
               class="conditions_ri">
            <img src="../../../../assets/mspbots/mapping/add-circle-plus.png"
                 alt="">
            Add Template
          </div>
        </el-popover>

      </div>
      <div class="temp_content"
           >
        <div class="tempList" v-loading="listLoading">
          <div class="item_temp_blank"
               v-for="(item) in currTempList"
               :key="item.id">
            <div class="item_temp">
              <div class="item_temp_label"
                   @click="templateDetil(item)">
                <span v-if="item.name.length<85">{{item.name}}</span>
                <el-tooltip :open-delay="1000" v-else
                            class="item"
                            effect="dark"
                            :content="item.name"
                            placement="top">
                  <span>{{item.name.substring(0,120)+'...'}}</span>
                </el-tooltip>
                <span style="padding-left:10px;font-size: 12px;color:#bfbfbf;">{{item.type=== 1?'Profit & Loss Statement':item.type===2?'Balance Sheet':''}}</span>
              </div>
              <div class="temp_btn_grounp_box">
                <div class="temp_share_text"
                     v-if="!item.modifyFlag"><span>{{$t('custom.mapping.buildInTemplate')}}</span></div>
                <div class="temp_btn_grounp">
                  <!-- <div class="accounts_btn edit_btn" @click="editAccount($event,item)"></div> -->
                  <div v-if="item.modifyFlag">
                    <updataTemplate :popData="item"
                                  :modifyFlag="item.modifyFlag"
                                  :integrationCode="integrationCode"
                                  @refreshTemp="refreshTempList"
                                  @refreshEditTempList="init"></updataTemplate>
                  </div>
                  <!-- <div class="accounts_btn delete_btn" @click="deleteTemp(item.id)"></div> -->
                  <el-popconfirm v-if="item.modifyFlag"
                                :title="$t('custom.workSchedule.template.sureDeleteTips')"
                                 @confirm="deleteTemp(item.id)"
                                 :cancel-button-text="$t('custom.workSchedule.template.cancel')"
                                 :confirm-button-text="$t('custom.workSchedule.template.confirm')">
                    <!-- <span slot="reference"
                              class="accounts_btn delete_btn"></span> -->
                    <div slot="reference"
                         class="accounts_btn delete_btn"></div>
                  </el-popconfirm>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <editAccountItem v-if="editAccountVisible"
                     :account="accountItem"
                     ref="editAccountItem"
                     @refreshTemp="refreshTempList"></editAccountItem>
  </div>
</template>
<script>
import editAccountItem from './editAccountItem'
import updataTemplate from './update-template'
// import { isIncludeSymbol } from '@/utils/validate'
export default {
  components: {
    editAccountItem,
    updataTemplate
  },
  data () {
    return {
      dialogVisible: false,
      filterText: '',
      visible: false,
      checked: false,
      selectValue: '',
      editAccountVisible: false,
      accountItem: null,
      accountTitle: '',
      listLoading: false,
      addLoading: false,
      accountId: '',
      dataForm: {
        name: '',
        tempId: '',
        type: 1
      },
      listData: [],
      tempDateList: [],
      copyTempDateList: [],
      currTempList: [],
      falg: true,
      options: [{
        label: 'Profit & Loss Statement',
        value: 1
      },
      {
        label: 'Balance Sheet',
        value: 2
      }
        // {
        //   label: 'Cash Flow Statement',
        //   value: '3'
        // }
      ]
    }
  },
  props: {
    optionType: {
      type: Number
    },
    integrationCode: {
      type: String
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: this.limitNameLength, trigger: 'blur' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        tempId: [
          { validator: this.checkCopyFrom, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.reqTempList()
      this.copyReqTempList()
    },
    refreshTempList () {
      this.$emit('refreshList')
    },
    refreshEditTempList () {
      this.init()
    },
    reqTempList () {
      this.listLoading = true
      this.$interface.mapping.requstTempList({ integrationCode: this.integrationCode })
        .then(({ data: res }) => {
          this.currTempList = []
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.tempDateList = res.data
          this.currTempList = this.tempDateList

          this.listLoading = false
        })
        .catch(() => { })
    },
    copyReqTempList () {
      // this.listLoading = true
      this.$interface.mapping.requstTempList({ type: this.dataForm.type, integrationCode: this.integrationCode })
        .then(({ data: res }) => {
          // this.listLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.copyTempDateList = res.data
        })
        .catch(() => { })
    },
    handleClose (done) {
      this.filterText = ''
      done()
    },
    addPopverClose () {
      this.checked = false
      this.$refs['newMappingForm'].resetFields()
    },
    dataFormSubmitHandle () {
      this.addLoading = true
      this.$refs['newMappingForm'].validate().then(() => {
        if (!this.checked) this.addManageTemp()
        else this.copyManageFromTemp()
      }).catch(() => {
        this.addLoading = false
        this.falg = true
      })
    },
    tempalteChange () {
      this.copyTempDateList = []
      this.copyReqTempList()
    },
    addManageTemp () {
      if (this.falg) {
        this.falg = false
        this.$interface.mapping.addTemplate({
          name: this.dataForm.name,
          type: this.dataForm.type,
          integrationCode: this.integrationCode
        }).then(({ data: res }) => {
          this.addLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$emit('refreshList')
          this.visible = false
          this.init()
          this.falg = true
        }).catch(() => {
          this.addLoading = false
          this.falg = true
        })
      }
    },
    copyManageFromTemp () {
      if (this.falg) {
        this.falg = false
        this.$interface.mapping.copyFromTemp({
          name: this.dataForm.name,
          id: this.dataForm.tempId,
          type: this.dataForm.type
        }).then(({ data: res }) => {
          this.addLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$emit('refreshList')
          this.visible = false
          this.init()
          this.falg = true
        }).catch(() => {
          this.addLoading = false
          this.falg = true
        })
      }
    },
    searchTemp (name) {
      this.currTempList = this.tempDateList.filter(e => e.name.toLowerCase().indexOf(name.toLowerCase()) !== -1)
    },
    limitNameLength (rule, value, callback) {
      if (value.length > 85) callback(new Error('Limit the name within 85 characters'))
      callback()
    },
    validatePass (rule, value, callback) {
      let params = {
        name: value.trim(),
        isNew: true,
        accountId: ''
      }
      this.$interface.reports.postCheckNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error('The name is already exists'))
          }
          callback()
        }).catch(() => { this.addLoading = false })
    },
    checkCopyFrom (rule, value, callback) {
      if (this.checked) {
        if (!this.dataForm.tempId) return callback(new Error('Please Select'))
        else callback()
      } else {
        callback()
      }
    },
    editAccount (e, item) {
      e.stopPropagation()
      // this.editAccountVisible = true
      // this.accountItem = item
      // this.$nextTick(() => {
      //   this.$refs.editAccountItem.dialogVisible = true
      // })
    },
    templateDetil (item) {
      this.editAccountVisible = true
      this.accountItem = item
      this.$nextTick(() => {
        this.$refs.editAccountItem.dialogVisible = true
      })
    },
    deleteTemp (id) {
      this.listLoading = true
      this.$interface.mapping.deleteTemp({
        id: id
      }).then(({ data: res }) => {
        this.listLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$emit('refreshList')
        this.$message({
          type: 'success',
          message: 'success!'
        })
        this.init()
      }).catch(() => { this.listLoading = false })
    }
  }
}
</script>
<style lang="scss">
.manage_accounts {
  .el-dialog__header {
    padding: 14px 20px;
    box-shadow: 0px 1px 0px 0px #f0f0f0;
  }
  .el-dialog__headerbtn {
    top: 18px;
  }
  .el-dialog__body {
    padding: 0;
  }
  .accounts_conditions {
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 48px;
    box-shadow: 0px 1px 0px 0px #f0f0f0;
    .el-input {
      width: 180px;
    }
    .conditions_ri {
      font-size: 14px;
      font-weight: 400;
      color: #138dc7;
      line-height: 20px;
      cursor: pointer;
      display: flex;
      align-items: center;
      img {
        width: 14px;
        height: 14px;
        margin-right: 10px;
      }
    }
  }
  .temp_content {
    max-height: 50vh;
    min-height: 200px;
    overflow-y: auto;
    .tempList {
      padding-bottom: 20px;
      .item_temp_blank {
        padding: 0 20px;
      }
      .item_temp_blank:hover {
        background-color: #f5f7fa;
      }
      .item_temp_blank:hover .temp_btn_grounp {
        display: flex;
      }
      .item_temp {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 48px;
        box-shadow: 0px 1px 0px 0px #f0f0f0;
        .item_temp_label {
          flex: 1;
          height: 100%;
          display: flex;
          align-items: center;
        }
        .temp_btn_grounp_box {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .temp_share_text {
            min-width: 80px;
            height: 20px;
            text-align: center;
            line-height: 20px;
            border-radius: 3px;
            padding: 0px 14px;
            background-color: #eef5dc;
            color: #8bbb11;
          }
        }
        .temp_btn_grounp {
          // visibility: hidden;
          display: none;
          justify-content: space-between;
          align-items: center;
          max-width: 66px;
          .accounts_btn {
            width: 28px;
            height: 28px;
            display: inline-block;
            background-size: 14px;
            background-position: center;
            background-repeat: no-repeat;
            cursor: pointer;
          }
          .accounts_btn:hover {
            background-color: #e6f7ff;
          }
          .edit_btn {
            margin-right: 10px;
            background-image: url("../../../../assets/mspbots/qa-bot/edit-bot-block.png");
          }
          .edit_btn:hover {
            background-image: url("../../../../assets/mspbots/mapping/action_edit.png");
          }
          .delete_btn {
            background-image: url("../../../../assets/mspbots/qa-bot/escalation_delete.png");
          }
          .delete_btn:hover {
            background-image: url("../../../../assets/mspbots/mapping/action_delete.png");
          }
        }
      }
    }
  }
}
.manage_accounts_addtemp {
  .el-form-item__label:before {
    content: "" !important;
    margin-right: 0;
  }
  .el-form-item {
    margin-bottom: 10px;
    button {
      width: 100%;
      margin-top: 20px;
    }
  }
  .el-form-item__label {
    padding: 0;
  }
}
.manage_account_selecet {
  .temp_share_text {
    width: 80px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    border-radius: 3px;
    padding: 0px 14px;
    background-color: #eef5dc;
    color: #8bbb11;
    font-size: 12px;
    margin-left: 20px;
  }
}
</style>
